package org.basis.algorithm.sort.practice;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

/**
 * @author Mr_wenpan@163.com 2022/02/28 10:54
 */
public class Test {

    public static void main(String[] args) throws InterruptedException {
        Object obj = new Object();
        AtomicBoolean nowA = new AtomicBoolean(true);
        // 第一个线程
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                synchronized (obj) {
                    while (!nowA.get()) {
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    nowA.set(false);
                    System.out.print("A");
                    obj.notify();
                }


            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                synchronized (obj) {
                    while (nowA.get()) {
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    nowA.set(true);
                    System.out.print("B");
                    obj.notify();
                }
            }
        }).start();

        TimeUnit.SECONDS.sleep(1);
        System.out.println();

        Thread t1 = new Thread(() -> {
            LockSupport.park();
            System.out.print("A");
        });

        Thread t2 = new Thread(() -> {
            System.out.print("B");
            LockSupport.unpark(t1);
        });

        t1.start();
        t2.start();
    }
}
